@file:OptIn(ExperimentalMaterial3Api::class)

package com.fishingwithme.android.ui.screens.spots

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MyLocation
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.ImageUploader
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.SpotUpdateViewModel
import com.fishingwithme.android.utils.EventBus
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UpdateSpotScreen(
    id: String,
    navController: NavController,
    viewModel: SpotUpdateViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val coroutineScope = rememberCoroutineScope()
    var hasLoadedData by remember { mutableStateOf(false) }

    if (uiState.props.fishTypes.isEmpty() && !uiState.isLoading && !hasLoadedData) {
        viewModel.loadProps()
        viewModel.loadSpotData(id)
        hasLoadedData = true
    }

    // Listen for map data events
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            try {
                EventBus.mapDataEvent.collect { event ->
                    val mapData = event.data

                    if (mapData.containsKey("navigationPoints")) {
                        val navPoints = mapData["navigationPoints"] as? List<*>
                        if (navPoints != null) {
                            val positions = navPoints.mapNotNull { point ->
                                if (point is Map<*, *>) {
                                    val lat = point["latitude"] as? Double ?: 0.0
                                    val lng = point["longitude"] as? Double ?: 0.0
                                    Position(lat, lng)
                                } else {
                                    null
                                }
                            }
                            if (positions.isNotEmpty()) {
                                viewModel.updateLocation(
                                    positions[0].latitude,
                                    positions[0].longitude
                                )
                                viewModel.updatePoints(positions)
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("UpdateSpotScreen", "${e.message}")
            }
        }
    }

    // Listen for save success state
    LaunchedEffect(uiState.isSaveSuccess) {
        if (uiState.isSaveSuccess && !uiState.isLoading) {
            // Log for debugging
            android.util.Log.d("UpdateSpotScreen", "Save successful, navigating back")
            // Navigate back to the previous screen
            // Try popBackStack first, fallback to navigateUp if needed
            if (!navController.popBackStack()) {
                navController.navigateUp()
            }
            // Reset the save state after a short delay to ensure navigation completes
            kotlinx.coroutines.delay(100)
            viewModel.resetSaveState()
        }
    }

    suspend fun onPictureUpload(file: File): Flow<Result<String>> {
        return viewModel.uploadFile(file)
    }

    // Optimized UI components - improved performance version
    @Composable
    fun RadioButtonWithLabel(label: String, selected: Boolean, onSelect: () -> Unit) {
        // Direct color configuration, MaterialTheme will automatically manage
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(AppDimensions.SPACING_8)
                .clickable(enabled = !uiState.isLoading) { if (!uiState.isLoading) onSelect() }
        ) {
            RadioButton(
                selected = selected,
                onClick = { if (!uiState.isLoading) onSelect() },
                colors = RadioButtonDefaults.colors(
                    selectedColor = MaterialTheme.colorScheme.primary,
                    unselectedColor = MaterialTheme.colorScheme.onSurfaceVariant
                ),
                enabled = !uiState.isLoading
            )
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
            Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }

    @Composable
    fun CheckboxWithLabel(label: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
        // Direct color configuration, MaterialTheme will automatically manage
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(AppDimensions.SPACING_8)
                .clickable(enabled = !uiState.isLoading) { if (!uiState.isLoading) onCheckedChange(!checked) }
        ) {
            Checkbox(
                checked = checked,
                onCheckedChange = { if (!uiState.isLoading) onCheckedChange(it) },
                colors = CheckboxDefaults.colors(
                    checkedColor = MaterialTheme.colorScheme.primary,
                    uncheckedColor = MaterialTheme.colorScheme.onSurfaceVariant,
                    checkmarkColor = MaterialTheme.colorScheme.onPrimary
                ),
                enabled = !uiState.isLoading
            )
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
            Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }

    // PropertySection component, make title parameter optional
    @Composable
    fun PropertySection(title: String = "", content: @Composable () -> Unit) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_12),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            ),
            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
        ) {
            Column(modifier = Modifier.padding(AppDimensions.SPACING_4)) {
                if (title.isNotEmpty()) {
                    Text(
                        text = title,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(bottom = AppDimensions.SPACING_12)
                    )
                }
                content()
            }
        }
    }

    // Optimized 3-column grid layout - improved performance version
    @Composable
    fun ThreeColumnGrid(items: List<@Composable () -> Unit>) {
        // Direct rendering, reduce extra composition layers
        Column {
            // Calculate how many rows are needed
            val rowCount = (items.size + 2) / 3

            // Render row by row
            for (i in 0 until rowCount) {
                // Calculate the starting index of the current row
                val startIndex = i * 3

                Row(modifier = Modifier.fillMaxWidth()) {
                    // Position 1
                    if (startIndex < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    // Position 2
                    if (startIndex + 1 < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex + 1]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    // Position 3
                    if (startIndex + 2 < items.size) {
                        Box(modifier = Modifier.weight(1f)) {
                            items[startIndex + 2]()
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }
                }
            }
        }
    }

    Scaffold(
        containerColor = MaterialTheme.colorScheme.background
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize()) {
            // Form content - use LazyColumn instead of Column+verticalScroll to improve performance
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(AppDimensions.SPACING_16),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_16),
                content = {
                    // Photo upload
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_8)) {
                                PropertySection() {
                                    ImageUploader(
                                        pictures = uiState.photos,
                                        maxImages = 5,
                                        onPicturesChanged = { newPictures ->
                                            if (!uiState.isLoading) {
                                                viewModel.updatePhotos(newPictures)
                                            }
                                        },
                                        onImageUpload = { file ->
                                            onPictureUpload(file)
                                        }
                                    )
                                }
                            }
                        }
                    }

                    // Spot name
                    item {
                        OutlinedTextField(
                            value = uiState.spotName,
                            onValueChange = { if (!uiState.isLoading) viewModel.updateSpotName(it) },
                            label = {
                                Text(
                                    stringResource(R.string.spot_name),
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            enabled = !uiState.isLoading,
                            colors = TextFieldDefaults.outlinedTextFieldColors(
                                focusedTextColor = MaterialTheme.colorScheme.onSurface,
                                unfocusedTextColor = MaterialTheme.colorScheme.onSurface,
                                cursorColor = MaterialTheme.colorScheme.primary,
                                focusedBorderColor = MaterialTheme.colorScheme.primary,
                                unfocusedBorderColor = MaterialTheme.colorScheme.outline
                            )
                        )
                    }

                    // Location information
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                PropertySection(title = stringResource(R.string.location_info)) {
                                    // Display currently selected latitude and longitude
                                    if (uiState.latitude != 0.0 && uiState.longitude != 0.0) {
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Column {
                                                Text("纬度: ${uiState.latitude}")
                                                Text("经度: ${uiState.longitude}")
                                            }
                                        }
                                    }

                                    // Action buttons
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.End,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        // Jump to map selection button
                                        Button(
                                            onClick = {
                                                if (!uiState.isLoading) {
                                                    val router =
                                                        "${FishingNavigation.MAP_SPOT_NAV_UPDATE}?moduleKey=updateSpot&spotId=${uiState.id}"
                                                    navController.navigate(router)
                                                }
                                            },
                                            enabled = !uiState.isLoading,
                                            modifier = Modifier.padding(AppDimensions.SPACING_8)
                                        ) {
                                            Text("在地图上选择")
                                        }

                                        // Use current location button
                                        if (uiState.currentLocation != null) {
                                            TextButton(
                                                onClick = {
                                                    if (!uiState.isLoading) {
                                                        viewModel.updateLocation(
                                                            uiState.currentLocation!!.latitude,
                                                            uiState.currentLocation!!.longitude
                                                        )
                                                    }
                                                },
                                                enabled = !uiState.isLoading
                                            ) {
                                                Icon(
                                                    Icons.Default.MyLocation,
                                                    contentDescription = null,
                                                    modifier = Modifier.size(AppDimensions.ICON_SIZE_16)
                                                )
                                                Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
                                                Text("使用当前位置")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Parking convenience
                    item {
                        PropertySection(title = stringResource(R.string.parking_convenience)) {
                            ThreeColumnGrid(
                                listOf(
                                    {
                                        RadioButtonWithLabel(
                                            label = stringResource(R.string.convenient),
                                            selected = uiState.parkingEasy,
                                            onSelect = { viewModel.updateParkingEasy(true) }
                                        )
                                    },
                                    {
                                        RadioButtonWithLabel(
                                            label = stringResource(R.string.inconvenient),
                                            selected = !uiState.parkingEasy,
                                            onSelect = { viewModel.updateParkingEasy(false) }
                                        )
                                    }
                                ))
                        }
                    }

                    // Spot level
                    item {
                        PropertySection(title = stringResource(R.string.spot_level)) {
                            val levels = uiState.props.lvls
                            ThreeColumnGrid(levels.map { level ->
                                {
                                    RadioButtonWithLabel(
                                        label = level.name,
                                        selected = uiState.selectedLevel == level.code,
                                        onSelect = { viewModel.updateSelectedLevel(level.code) }
                                    )
                                }
                            })
                        }
                    }

                    // Distance to water
                    item {
                        PropertySection(title = stringResource(R.string.distance_to_water)) {
                            val distances = uiState.props.distances
                            ThreeColumnGrid(distances.map { distance ->
                                {
                                    RadioButtonWithLabel(
                                        label = distance.name,
                                        selected = uiState.selectedDistance == distance.code,
                                        onSelect = { viewModel.updateSelectedDistance(distance.code) }
                                    )
                                }
                            })
                        }
                    }

                    // Water type
                    item {
                        PropertySection(title = stringResource(R.string.water_type)) {
                            val waterTypes = uiState.props.waterTypes
                            ThreeColumnGrid(waterTypes.map { waterType ->
                                {
                                    RadioButtonWithLabel(
                                        label = waterType.name,
                                        selected = uiState.selectedWaterType == waterType.code,
                                        onSelect = { viewModel.updateSelectedWaterType(waterType.code) }
                                    )
                                }
                            })
                        }
                    }

                    // Spot type
                    item {
                        PropertySection(title = stringResource(R.string.spot_type)) {
                            val spotTypes = uiState.props.spotTypes
                            ThreeColumnGrid(spotTypes.map { spotType ->
                                {
                                    CheckboxWithLabel(
                                        label = spotType.name,
                                        checked = uiState.selectedSpotType.contains(spotType.code),
                                        onCheckedChange = {
                                            viewModel.toggleSpotType(spotType.code)
                                        }
                                    )
                                }
                            })
                        }
                    }

                    // Fish species
                    item {
                        PropertySection(title = stringResource(R.string.fish_species)) {
                            val fishTypes = uiState.props.fishTypes
                            ThreeColumnGrid(fishTypes.map { fishType ->
                                {
                                    CheckboxWithLabel(
                                        label = fishType.name,
                                        checked = uiState.selectedFishTypes.contains(fishType.code),
                                        onCheckedChange = {
                                            viewModel.toggleFishType(fishType.code)
                                        }
                                    )
                                }
                            })
                        }
                    }

                    // Basic properties
                    item {
                        PropertySection(title = stringResource(R.string.basic_properties)) {
                            ThreeColumnGrid(
                                listOf(
                                    {

                                        CheckboxWithLabel(
                                            label = stringResource(R.string.paid_spot),
                                            checked = uiState.isFree,
                                            onCheckedChange = { viewModel.updateIsFree(it) }
                                        )

                                    },
                                    {

                                        CheckboxWithLabel(
                                            label = stringResource(R.string.forbidden_fishing),
                                            checked = uiState.isForbidden,
                                            onCheckedChange = { viewModel.updateIsForbidden(it) }

                                        )
                                    },
                                    {

                                        CheckboxWithLabel(
                                            label = stringResource(R.string.public_spot),
                                            checked = uiState.isPrivate,
                                            onCheckedChange = { viewModel.updateIsPrivate(it) }
                                        )


                                    }
                                ))
                        }
                    }

                    // Description
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            ),
                            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_2)
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                PropertySection() {
                                    OutlinedTextField(
                                        value = uiState.description,
                                        onValueChange = {
                                            if (!uiState.isLoading) viewModel.updateDescription(it)
                                        },
                                        placeholder = { Text("请输入钓点描述，如鱼情、水深等信息") },
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .height(AppDimensions.CARD_HEIGHT_150),
                                        maxLines = 10,
                                        enabled = !uiState.isLoading
                                    )
                                }
                            }
                        }
                    }

                    // Submit button
                    item {
                        Button(
                            onClick = { viewModel.updateSpot() },
                            enabled = uiState.spotName.isNotBlank() && uiState.photos.isNotEmpty() &&
                                    uiState.selectedSpotType.isNotEmpty() && uiState.selectedFishTypes.isNotEmpty() &&
                                    !uiState.isLoading,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(stringResource(R.string.update_spot))
                        }
                    }
                }
            )

            // Loading overlay
            if (uiState.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background.copy(alpha = 0.7f))
                        .clickable(enabled = false) {},
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(AppDimensions.ICON_SIZE_48)
                    )
                }
            }
        }
    }
}